import validFunc from './validate'
import $ from 'jquery'

/**
 * Created by xieze on 2016/11/22.
 * email xieze333@163.com
 */
window.validFunc = validFunc
var insert_name_arr = []//新增数据的name名
let creatUi = function () {
  //回到顶部按钮
  $(window).scroll(function () {
    if ($(window).scrollTop() > 300) {
      $('.myscrollTop').show()
    }
    else {
      $('.myscrollTop').hide()
    }
  })
  var self = this
  var $table //datatable
  var checkFlag, operationFlag
  //重组数据
  self.reCreatData = function (type) {
    // type add:字段以搜索面板为准
    // console.log(returnData,data,type)
    // 默认列数样式配置
    var _this = this;
    var option = _this[type];

    // console.log(newReturn)
    var parms = {
      enter_value: '', // 待提交数据
      enter_data: {}, // 存储特殊情况下待提交数据
      enter_string: '',
      disabled: false,
      visible: true,
      enter_arr: [],
      init: true,
      el: null,
      column: option.column || 1 // 默认1列 面板分类覆盖默认，字段分列覆盖面板
    }

    // 只重组默认面板数据
    $.each(option.field, function (i1, n2) {
      for (let i in parms) {
        if (typeof n2[i] == 'undefined') {
          _this.$set(n2, i, parms[i]);
        }
      }
      if (n2.column) {
        n2.column = 24 / n2.column;
      }

    })

  }

  /**
   * 通用新增函数
   * option
   * self : vueSelf,
   * content : $(".popwin-insert"),
   * title : "编辑车辆",
   * url : "vehicle/update.htm",
   * index:index,
   * type : "vue" 默认不传为js弹窗
   * error:function
   * easyflow: 面板（比如insert,newInsert,search等)
   **/
  self.add = function (option) {
    var easyflow = option.easyflow || option.self.newInsert;
    $.each(easyflow.field, function (i, n) {
      n.init = true;   // 为新增编辑设回初始状态
      $(n.el).find(".valid_message").removeClass("in");
    });
    // console.log(option.self.newInsert.field);
    var carinsertDialog = fx.dialog({
      msg: option.content,
      title: option.title,
      width: option.width || 500,
      onshow: option.onshow,
      // fixed:false,
      // left:option.left ,
      // top:option.right,
      easyflow: option.easyflow,
      okey: function () {
        // 提交前回调
        if (option.okey) {
          option.okey();
        }
        var newInsert = easyflow.field;
        // 确定事件 校验开始
        if (!validFunc.check(newInsert)) {
          return false;
        }
        var postParms = self.getPostData(newInsert, "init");
        // 提交前回调
        console.log('postParms', postParms);
        if (typeof (option.before) == "function") {
          if (option.before(postParms)) {
            return false;
          }
        }

        if (option.url && option.url != "") {
          window.VM.axios({
            url: option.url,
            data: postParms
          }).then(function (rs) {
            const data = rs.data;

            console.log('option.url', option.url);
            // 提交后回调
            if (typeof (option.after) == "function") {
              if (option.after(data, postParms)) {
                return false;
              }
            }
            ;
            // 有查询功能才查询
            if (typeof (option.self.searchData) == "function") {
              option.self.searchData();
            }
            //remove:初始化，把弹窗内容清空
            carinsertDialog.close().remove();
          });
        }

        return false

      },
      onremove: function () {
        if (option.onremove) {
          option.onremove();
        }
        // 清空enter_value
        $.each(easyflow.field, function (i, n) {
          n.init = true;
          if (n.checked) {
            n.checked = false;
          }
          n.enter_value = "";   // 为新增编辑设回初始状态
          n.enter_data = {};
          n.enter_string = "";
          n.enter_arr = []
        });
      }
    });

    return carinsertDialog;
  };

  // add 弹窗初始化(提供给vue自带弹窗)
  self.easyflowAddInit = function (option) {
    $.each(option.easyflow.field, function (i, n) {
      n.init = true   // 为新增编辑设回初始状态
      $(n.el).find('.valid_message').removeClass('in')
    })
  }
  // add 确定事件
  self.easyflowOk = function (option) {
    var vm = this;
    // console.log(vm, option, vm[option.easyflow])
    var errorFn = option.error || null
    option.url = option.url || ''
    var easyflow = vm[option.easyflow];
    console.log("easyflowOk", easyflow)
    // 确定事件 校验开始
    if (!validFunc.check(easyflow.field)) {
      // console.log(easyflow.field)
      return false
    }
    $('.modal-card-foot ').find('.is-primary').addClass(' is-loading')
    easyflow.isLoading = true

    var postParms = self.getPostData(easyflow.field, 'init')
    // 提交前回调
    if (typeof (option.before) == 'function') {
      if (option.before(postParms)) {
        return false
      }
    }
    if (option.url && option.url != '') {

      vm.axios({
        url: option.url,
        data: postParms
      }).then(function (res) {
        const data = res.data;
        // console.log(easyflow)
        easyflow.isLoading = false
        easyflow.isShow = false
        // console.log(option.url)
        // 提交后回调
        if (typeof (option.after) == 'function') {
          if (option.after(data, postParms)) {
            return false
          }
        }
        // 有查询功能才查询
        if (typeof (vm.searchData) == 'function' && vm.search.url != '' && vm.search.url) {
          vm.searchData()
        }

        // 清空enter_value
        $.each(easyflow.field, function (i, n) {
          n.init = true
          if (n.checked) {
            n.checked = false
          }
          n.enter_value = ''   // 为新增编辑设回初始状态
          n.enter_data = {}
          n.enter_string = ''
          n.enter_arr = []
          $(n.el).find('.valid_message').removeClass('in')
          if (n.edit_disabled) {
            n.disabled = false
          }
        })

        // vm.$notify.success({content:'success！'});
        $('.modal-card-foot ').find('.is-primary').removeClass(' is-loading')
      }).catch(function (msg) {
        // 请求失败
        easyflow.isShow = false
        easyflow.isLoading = false
        // 清空enter_value
        $.each(easyflow.field, function (i, n) {
          n.init = true
          if (n.checked) {
            n.checked = false
          }
          n.enter_value = ''   // 为新增编辑设回初始状态
          n.enter_data = {}
          n.enter_string = ''
          n.enter_arr = []
          $(n.el).find('.valid_message').removeClass('in')
          if (n.edit_disabled) {
            n.disabled = false
          }
        })
        // vm.$notify.success({content:'success！'});
        $('.modal-card-foot ').find('.is-primary').removeClass(' is-loading')
        // vm.$notify.danger({'content':data.errorMsg});
      })
    } else {
      $('.modal-card-foot ').find('.is-primary').removeClass(' is-loading')
    }

  }
  // 删除事件
  self.easyflowDele = function (option) {
    var vm = this;
    // console.log(vm)
    var deleField = option.easyflow.field
    var row = option.easyflow.row
    var newParms = {}
    for (var i = 0; i < deleField.length; i++) {
      var name = deleField[i].name
      //   if(Object.prototype.toString.call(deleField[i].type) === "[object Array]"){
      //     // 数组不做处理
      newParms[name] = row[name]
      //   }else if( deleField[i].type == "long" || deleField[i].type == "float" ){
      //         newParms[name] = parseInt(row[name]);
      //   }else if(deleField[i].type == "integer" || deleField[i].type == "double" ){
      //         newParms[name] = Number(row[name]);
      //   }else{
      //         newParms[name] = row[name].toString();
      //   }
    }
    var postParms = newParms
    // var postParms = {name: vm.easyflowName,parms: newParms};
    // 提交前回调
    if (typeof (option.before) == 'function') {
      if (option.before(postParms)) {
        return false
      }
    }

    vm.axios({
      url: option.url,
      data: newParms
    }).then(function (rs) {
      const data = rs.data;


      // console.log(option.url)
      if (typeof (vm.searchData) == 'function') {
        vm.searchData()
      }

      // 提交后回调
      if (typeof (option.after) == 'function') {
        if (option.after(data, postParms)) {
          return false
        }
      }


    })

  }

  // add 关闭事件
  self.easyflowCancel = function (option) {
    // 清空enter_value
    $.each(option.easyflow.field, function (i, n) {
      n.init = true
      if (n.checked) {
        n.checked = false
      }
      n.enter_value = ''   // 为新增编辑设回初始状态
      n.enter_data = {}
      n.enter_string = ''
      n.enter_arr = []
      $(n.el).find('.valid_message').removeClass('in')
      if (n.edit_disabled) {
        n.disabled = false
      }
    })
  }
  // 初始化编辑数据
  self.easyflowEditInit = function (option) {
    var _this = option.content
    setTimeout(() => {
      const field = option.easyflow.field;
      $.each(field, function (i1, n1) {
        n1.init = true  //为新增编辑设回初始状态
        if (n1.edit_disabled) {
          n1.disabled = true
        }
      })
        $.each(option.row, function (i, n) {
          if (field[i]) {
            if (field[i].ui == 'radio_choose') {
              var value4Vue1 = []

              if (!field[i].value4Vue) {
                return
              } else {
                for (var i2 = 0; i2 < field[i].value4Vue.length; i2++) {
                  var splVal = field[i].value4Vue[i2].split('=')

                  if (n == splVal[0] || n == splVal[1]) {
                    field[i].enter_value = splVal[0]
                    field[i].enter_string = splVal[1]
                  }
                }
              }
            } else if (field[i].ui == 'suggestbox') {
              if (i == 'content' && i != null) {
                field[i].enter_value = n
                field[i].enter_string = n
              } else {
                var value4Vue1 = []
                if (!field[i].value4Vue) {
                  return
                } else {

                  for (var i2 = 0; i2 < field[i].value4Vue.length; i2++) {
                    var splVal = field[i].value4Vue[i2].split('=')

                    if (n == splVal[1]) {

                      field[i].enter_value = splVal[0]
                      field[i].enter_string = splVal[1]

                    }
                  }
                }
              }

            } else {
              field[i].enter_value = n || '';
            }

          }
        })

    //  初始化完毕 回调
    //   if(typeof option)
    }, 160)
  }
  // 通用获取enter_value数据
  self.getPostData = function (field, type) {

    var postParms = {}
    $.each(field, function (i, n) {
      // 新增时更改初始状态
      if (type == 'init') {
        console.log(0)
        n.init = true
      }
      // 提交前转换格式string integer long float double date timestamp time
      if (Object.prototype.toString.call(n.enter_value) === '[object Array]') {
        console.log(1)
        // 数组不做处理
        postParms[n.name] = n.enter_value
      } else if (n.type == 'long' || n.type == 'float') {
        console.log(2)
        postParms[n.name] = parseInt(n.enter_value)
      } else if (n.type == 'integer' || n.type == 'double') {
        console.log(3)
        postParms[n.name] = Number(n.enter_value)
      } else {
        if (n.enter_value || n.enter_value == '0') {
          postParms[n.name] = $.trim(n.enter_value).toString()
        } else {
          postParms[n.name] = $.trim(n.enter_value)
        }
      }
      // postParms[n.name] = n.enter_value;
      // 获取特殊待提交数据
      if (fx.isObjectEmpty(n.enter_data)) {
        $.each(n.enter_data, function (i1, n1) {
          postParms[i1] = n1
        })
      }

    })
    return postParms
  }
  /**
   * 根据筛选field中的对象
   * 例子：{name:"test"} //筛选name为“test”的field
   */
  self.filterField = function (field, condition) {
    if (!field) {
      console.warn('筛选对象为空！')
      return false
    }
    var item = null;
    $.each(field, function (i, n) {
      var flag = true
      $.each(condition, function (i1, n1) {
        if (n[i1] != n1) {
          flag = false
        }
      })
      if (flag) {
        item = n;
        return;
      }
    })
    return item;
  }
  let vueInitParm = {
    initData: {}
  }
  // initType="static" || initType="dev" 静态面板初始化方式
  self.startInitStatic = function () {
    // 自定义新增面板
    const _this = this;
    if (_this.newInsert) {
      self.reCreatData.call(_this, 'newInsert')
    }
    // 自定义查看面板
    if (_this.newCheck) {
      self.reCreatData.call(_this, 'newCheck')
    }
    // 搜索面板
    //console.log('_this.search',_this);
    if (_this.search) {
      self.reCreatData.call(_this, 'search')

      // _this.result.reTableDatas = [];  //查询返回的表格数据
    }
    // 删除面板
    if (_this.delete) {
      self.reCreatData.call(_this, 'delete')
      // console.log(_this.insert)
    }
    // 新增面板
    if (_this.insert) {
      self.reCreatData.call(_this, 'insert')
      // console.log(_this.insert)
    }
    // 自定义面板
    if (_this.custom) {
      self.reCreatData.call(_this, 'custom')
    }
  }
  // 初始面板 2018-7-10 其实只返回minis就可以了
  self.getInitMixins = function () {
    return [{
      data() {
        return {
          search: {
            searchCi: null,//搜索计时器
            loading: false,
            table: {
              operation: [],
            },
            // 分页控制（静态）
            pagination: {
              total: 0,       // 总数
              current: 1,      // 分页
              pageSize: 20,
              clear: false  // 回到页码1
            },
            bak: {
              pageSize: 20,
              pageIndex: 1,//第几页（下标）
            } //提交查询时候的查询条件数据
          },
          // 删除面板
          delete: {
            url: '',
            parms: []
          },
          result: {
            field: [],
            tableDatas: [],
            reTableDatas: []
          }
        };
      },
      beforeMount() {
        self.startInitStatic.call(this);
      },
      methods: {
        // 查询
        searchData: function (options) {
          var _this = this;
          _this.search.loading = true;
          // 默认值
          if (!options) {
            options = {}
          }
          // var da=a?initData.search.bak:initData.search.Data;
          // console.log(da,1111111111111111111)
          // console.log('searching',this);
          //获取搜索条件
          var searchField = _this.search.field
          var _tempValue
          $.each(searchField, function (i, n) {
            _tempValue = searchField[i].enter_value || ''
            //当组件为ztree时，把空转为null
            if (searchField[i].ui === 'userui-in' && searchField[i].UIConfig && searchField[i].UIConfig.ui === 'ztreebox' || searchField[i].ui === 'ztreebox') {
              if (typeof _tempValue === 'string') {
                if (_tempValue == '') _tempValue = null
              } else if (Object.prototype.toString.call(_tempValue) === '[object Array]') {
                if (_tempValue.length === 0) _tempValue = null
              }
            }
            _this.search.bak[i] = _tempValue
          })
          if (!options.type || options.type != 'changePage' || options.type == 'undefined') {
            // 清除分页，回到分页码1
            // console.log('清除分页，回到分页码1');
            // _this.search.pagination.clear = true;
            _this.search.bak.pageIndex = 1
            _this.search.pagination.pageSize = _this.search.bak.pageSize;
            _this.search.pagination.current = 1;
            // this.searchData({type: 'changePage'})
            // return;
          }
          // console.log("!options2");
          // initData.search.bak = parmsTemp;fpaginationClear
          // _this.result.reTableDatas = {};
          // 提交前回调
          if (typeof (_this.search.before) == 'function') {
            if (_this.search.before.call(this, _this.search.bak)) {
              return false
            }
          }

          // 静态数据查询
          if (_this.initType == 'static' || _this.initType == 'easyflow') {

            _this.axios({
              url: _this.search.url,
              data: _this.search.bak
            }).then((res) => {
              _this.search.loading = false;
              let data = res.data;
              // _this.pageLength = data.data.totalSize
              _this.search.pagination.total = data.data.totalSize
              if (data.data.content == '') {
                _this.$notify.warning({'content': '暂无数据！'})
                _this.result.reTableDatas = []
              } else {
                // console.log(data.data);
                _this.result.reTableDatas = data.data.content
              }

              if (typeof (_this.search.after) == 'function') {
                _this.search.after.call(_this, data);
              }

            })
            //   .catch((data) => {//当请求失败后，调用afterError函数
            //   if (typeof (_this.search.afterError) == 'function') {
            //     _this.search.afterError(data)
            //   } else {
            //     fx.error(data.errorMsg)
            //   }
            //
            // })
          }
        },
        onTableChange: function (params) {
          const _this = this;
          // var arrpage={
          //     pageSize:"10",
          //     pageIndex: 1,//第几页（下标）
          // };
          // if(params.pagination.pageSize){
          // arrpage.pageSize=params.pagination.pageSize;//每页几条
          _this.search.bak.pageSize = params.pagination.pageSize || 20
          _this.search.bak.pageIndex = Number(params.pagination.current)
          _this.search.pagination.current = Number(params.pagination.current)
          this.searchData({type: 'changePage'})
        },
      },
      mounted() {
        var _this = this
        // 静态数据模式下，加载完vue后调用查询
        if (_this.search) {
          if (_this.prerventInit != false) {

            //进入页面的时候执行一次查询
            _this.searchCi = setInterval(function (_this) {
              var f = true
              var a;
              for (a in _this.search.field) {
                f = f && !!_this.search.field[a].ready
              }
              if (_this.search.field) {
                if (a && f) {
                  clearInterval(_this.searchCi)
                  _this.searchData()
                }
              }
            }, 1000, _this)
          }
        }
      }

    }]
  }
}

export default creatUi
